package com.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.IUserService;
import com.example.utils.JWTUtils;
import com.example.utils.MD5Utils;
import com.example.utils.Result;
import com.example.vo.LoginVo;
import com.example.vo.RegisterVo;
import com.example.vo.ResetVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 * @author cyz
 * @since 2022-06-11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //用户注册
    @Override
    public Result register(RegisterVo registerVo) {
        //获取用户请求信息
        String username = registerVo.getUsername();
        String password = registerVo.getPassword();
        String nickname = registerVo.getNickname();
        String userImg = registerVo.getUserImg();

        //用户数据校验
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)||StringUtils.isEmpty(nickname)){
            return Result.fail(400,"信息不能为空");
        }else if(username.length()<6||username.length()>20){
            return Result.fail(400,"用户名长度必须为6到20位");
        }else if (password.length()<6||password.length()>32){
            return Result.fail(400,"密码长度必须为6到32位"   );
        }

        //判断用户名是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,registerVo.getUsername());
        List<User> users = userMapper.selectList(queryWrapper);

        //如果用户名不存在进行注册
        if (users.size()==0){
            String md5Pwd = MD5Utils.md5(password);
            User user = new User();
            user.setUsername(username);
            user.setPassword(md5Pwd);
            user.setNickname(nickname);
            user.setUserImg(userImg);
            int i = userMapper.insert(user);
            if (i>0){
                return Result.success(1);
            }else {
                return Result.fail(404,"数据异常");
            }
        }else {
            return Result.fail(400,"用户名已存在");
        }
    }

    //用户登录
    @Override
    public Result login(LoginVo loginVo) {
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        //用户数据校验
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            return Result.fail(400,"信息不能为空");
        }else if(username.length()<6||username.length()>20){
            return Result.fail(400,"用户名长度必须为6到20位");
        }else if (password.length()<6||password.length()>32){
            return Result.fail(400,"密码长度必须为6到32位");
        }
       //判断用户名是否存在
        User user = iUserService.find(username,password);
        if (user == null ){
            return Result.fail(10002,"用户名或密码错误");
        }
            String token = JWTUtils.createToken(user.getId());
                redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(user),1, TimeUnit.DAYS);
                return Result.success(token);
    }

    @Override
    public User find(String username, String password) {
        String md5Pwd = MD5Utils.md5(password);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        queryWrapper.eq(User::getPassword,md5Pwd);
        queryWrapper.last("limit 1");
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public Result info(String token) {
         User user1 = iUserService.check(token);
         if (user1==null){
             return Result.fail(1003,"token不合法");
         }
        User user = new User();
        BeanUtils.copyProperties(user1,user);
        return Result.success(user);
    }

    @Override
    public User check(String token) {
        //判断是否传入token
        if (StringUtils.isEmpty(token)){
            return null;
        }
        //解析token
        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
        //判断解析的token是否为空
        if (stringObjectMap == null){
            return null;
        }
        //判断用户信息是否为空
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (StringUtils.isEmpty(userJson)){
            return null;
        }
        //解析为json
        User userinfo = JSON.parseObject(userJson,User.class);
        return userinfo;
    }

    @Override
    public Result getlist(Integer pageNum, Integer pageSize, String userName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(User::getUsername,userName);
        Page<User> page = iUserService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

    @Override
    public Result reset(ResetVo resetVo) {
        String username = resetVo.getUsername();
        String oldPassword = resetVo.getOldPassword();
        String password = resetVo.getPassword();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
            return Result.fail(400,"用户不存在");
        }else {
            String md5Pwd = MD5Utils.md5(oldPassword);
            String newMd5Pwd = MD5Utils.md5(password);
            if (md5Pwd.equals(user.getPassword())){
                user.setPassword(newMd5Pwd);
                int i = userMapper.updateById(user);
                return Result.success("修改成功");
            }
            return Result.fail(400,"原密码错误");
        }

    }




}
